from django.shortcuts import render
from django.views import View
from rest_framework.views import APIView
from django.conf import settings
from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client
from . import models
from django.http import JsonResponse
from rest_framework.response import Response
from . import serializer
from collections import OrderedDict 
from  rest_framework.generics import ListAPIView
from django.core.paginator import Paginator
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection

# Create your views here.
class Goods(APIView):
    def get(self,request):
        # 商品频道及分类菜单
        dict = OrderedDict()
        channels = models.GoodsChannle.objects.order_by('group_id', 'sequence')
        for channel in channels:

            group_id = channel.group_id    # 获取当前组的id
            if group_id not in dict:
                 dict[group_id] = {'channels': []}
            cat1 = channel.category    # 获取当前频道的类别
            # 获取下一级分类
            cat = models.GoodsCategory.objects.filter(parent=cat1)
            list=[]
            for i in cat:
                list.append({'id':i.id,'name':i.name})
            dict[group_id]['channels'].append({
                'id': cat1.id,
                'name': cat1.name,
                'url': channel.url,
                'sub_cats': list
            })
        return Response(dict)


class FastDFSStroage(Storage):
        """定义FastDFS客户端类"""
        def __init__(self, base_url = None, client_conf = None):
            """
            初始化对象
            :param base_url:
            :param client_conf:
            """
            if base_url is None:
                base_url = settings.FDAS_URL
                # 'http://123.57.61.168:8888'
            self.base_url = base_url
            if client_conf is None:
                client_conf = settings.FDFS_CLIENT_CONF
                # FDFS_CLIENT_CONF = os.path.join(BASE_DIR, 'client.conf')
            self.client_conf = client_conf
        def _open(self, name, mode = 'rb'):
            """
            打开文件
            :param name:
            :param mode: 
            :return:
            """
            pass
        def _save(self, name, content):
            """
            保存文件
            :param name: 传入文件名
            :param content: 文件内容
            :return:保存到数据库中的FastDFSDE文件名
            """
            client = Fdfs_client(self.client_conf)
            ret = client.upload_by_buffer(content.read())
            
            if ret.get("Status") != "Upload successed.":
                raise Exception("upload file failed")
            file_name = ret.get("Remote file_id")
            return file_name

        def exists(self, name):
            """
            检查文件是否重复, FastDFS自动区分重复文件
            :param name:
            :return:
            """
            return False  # 不重复

        def url(self, name):
            """
            获取name文件的完整url
            :param name:
            :return:
            """
            return self.base_url + name


# 列表页
class SKUListView(APIView):
    """
    sku列表数据
    """
    # serializer_class = CategoriesListSerializer
    
    def get(self,request):
        """
        获取查询集
        """
        id = request.GET.get('id')
        sort = request.GET.get('sort')
        page = request.GET.get('page')
        if sort == 2:
            data = models.GoodsSku.objects.filter(category_id=int(id)).order_by('price')
        if sort == 3:
            data = models.GoodsSku.objects.filter(category_id=int(id)).order_by('-sales')
        else:
            data = models.GoodsSku.objects.filter(category_id=int(id)).order_by('-id')

        paginator = Paginator(data,1)
        try:
            page = int(page)
        except:
            page=1
        if page > paginator.num_pages:
            page = 1
        page = paginator.get_page(page)
        page_num = page.number #获取当前页
        # skus_page = paginator.page(page)
        # num_pages = paginator.num_pages
        # 显示当前页的前后两页
        page_range = list(range(max(page_num-2,1),page_num))+list(range(page_num,min(page_num+2,paginator.num_pages)+1))
        # 加上省略号
        if page_range[0]-1>=2:
            page_range.insert(0,"...")
        if paginator.num_pages - page_range[-1] >= 2:
            page_range.append('...')
        # 加上首页和尾页
        if page_range[0] != 1:
            page_range.insert(0,1)
        if page_range[-1] != paginator.num_pages:
            page_range.append(paginator.num_pages)
        list1=[]
        for i in page:
            list1.append({'img':i.default_image_url,'id':i.id,'name':i.name,'caption':i.caption,'price':i.price,'stock':i.stock})
        return Response({'list':list1,'page':page_range})


class CategoriesView(APIView):
    def get(self,request):
        id = request.GET.get('id')
        cat3 = models.GoodsCategory.objects.get(id=id)
        cat2 = cat3.parent   # 自关联获取二级,
        return Response({
                "cat2": cat2.name,
                "cat3": cat3.name
            })


class ShopDetail(APIView):
    def get(self,request):
        # 获取当前商品的规格信息
        id = request.GET.get('id')
        # 获取当前sku的信息
        sku = models.GoodsSku.objects.get(id=int(id))
        goods = sku.goods
        list1 = []
        # 获取sku的分类
        spec = models.GoodsSpecification.objects.filter(goods=sku.goods)
        # print(spec)
        for i in spec:
            # 获取规格选项
            dict_spec={}
            dict_spec['name']=i.name
            dict_spec['options'] = i.specificationoption_set.all().values('value').first()
            list1.append(dict_spec)
        sku = serializer.CategoriesListSerializer(instance=sku)
        good = serializer.GoodsspuSerializer(instance=goods)
        #,'good':good
        dict1 = {'sku':sku.data,'sku_spec':list1,'goods':good.data}
        # print(dict1)
        return Response(dict1)


class Stock(APIView):
    def get(self,request):
        id = request.GET.get('id')
        stock = request.GET.get('stock')
        sku_stock = models.GoodsSku.objects.get(id=int(id)).stock
        stock = sku_stock - int(stock)
        if stock>0:
            data = {'code':200}
        else:
            data = {'code':201}
        return Response(data)


class SKUHistoryView(APIView):
    """ 保存用户历史浏览记录 """
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        user_id = request.user.id
        redis_conn = get_redis_connection('default')
        history = redis_conn.lrange("history_{}".format(user_id),0, 4)
        skus = []
        # 为了保持查询出的用户浏览的顺序一致
        for sku_id in history:
            sku = models.GoodsSku.objects.get(id = sku_id)
            skus.append(sku)
        s = serializer.CategoriesListSerializer(skus, many=True)
        return Response(s.data)

    def post(self,request):
        try:
            models.GoodsSku.objects.get(id = request.data.get('sku_id'))
        except:
            return Response({'code':400})
        conn = get_redis_connection('default')
        # users在这里是放在上下文中的request，而不是直接的request
        user = request.user
        # 2.判断是否保存过
        conn.lrem("history_{}".format(user.id), 0,request.data.get('sku_id'))
        # 3.写入
        conn.lpush("history_{}".format(user.id),request.data.get('sku_id'))
        # 4.控制保存数量
        conn.ltrim("history_{}".format(user.id), 0, 5)
        return Response({'code':200})


class CartVIew(APIView):
    '''
        添加购物车
    '''
    permission_classes = (IsAuthenticated,)
    def post(self,request):
        params = request.data
        skuid = params.get('sku_id')
        count = int(params.get('count'))
        # 检查数据
        try:
            sku = models.GoodsSku.objects.get(id=skuid)
        except Exception as e:
            return Response({'code':201,'data':'商品查找失败！！！'})
        user = request.user
        # 用户已经登录，在Redis中保存
        conn = get_redis_connection('default')
        cart_key = 'cart_{}'.format(user.id)
        # 获取sku_id的值
        cart_count = conn.hget(cart_key,skuid)
        if cart_count:
            # 累加数量
            count+=int(cart_count)
        conn.hset(cart_key,skuid,count)
        return Response({'code':200,'data':'添加成功！'})

    def get(self,request):
        user = request.user
        conn = get_redis_connection('default')
        cart_key = 'cart_{}'.format(user.id)
        cart_dict = conn.hgetall(cart_key)
        price = 0
        counts = 0
        skus = {}
        for sku_id,count in cart_dict.items():
            sku = models.GoodsSku.objects.get(id=sku_id)
            total = sku.price*int(count)
            skus[str(sku_id)] = {'count':count,'total':total,'price_sku':sku.price,'sku_name':sku.name,'img':sku.default_image_url}
            price += total
            count += int(count)
        data = {
            'counts':counts,
            'price':price,
            'sku':skus
        }
        print(data)
        return Response(data)


'''
    MIIEowIBAAKCAQEAlWAI6RHh6kAjZAxIu6XPoo7izhCUQA/Oo2k2OVYHr8xRpb/C/c1ZGztgLRb1xmaILMmszWjIUobA0hSog9iwK3pTIngqf4Bf+N1J1QOBJBt/Sag9Ylrc1S/zebRdWfr2P2UExYlsqINPJ0RicJKCFaH3JuAjCc0CaTBUJvp70IkimwnbUPUrQAv4UpB64lRk39GLwufnYbv+7ljSEEtXHzawQ9IAoWJULe/T9mNXlcIjHyz3001cWLIP4nxlqmyV7T7nfSGXDcJkyOW7SQjakLgez3vJT+EkMuKBdkPklf9If4QP1bW7vj9EuBXKh1dRP9qXqU+iZPT/8ab4GjxhFQIDAQABAoIBAGcGOn8Nz2QyYnZxpoSNwxyaMkHv22AnxtycB0MaW+jbIgEQtps4U1nd5OKUcGUreIZzfpSZzXhl6n26s9Nj03XZQ5eFi8Iut4K8lVyusxZFRNB3kgbRJnh/Pw1U4gHafpaQxO69bsz269PobYC4+7GR6RXOBzyOQjhslc3gex8DOLIsHMKXoWZJHcdl190JCvLJvq+1VmF0q/mFdhHTTbCjnti29PDfgl+Ovziz2YOOJzuoufaz9dAAU8KXfMrxeVpQcZ4zJs7hPaAycLauOYR3JMIA0g1ayFidFL9+srd8SpcvflyG/keGA3UmWUx6G/u/LJx7brzvoHFhH7L3swECgYEAxTW1YfKddhT2+dTvUu9RiuB8QEdexscHr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